#ifndef PRICEGRABBER_H
#define PRICEGRABBER_H

#include <QObject>

#include <QMap>
#include <QSet>
#include <QQueue>
#include <QTime>
#include <QUrl>

class QWebFrame;
class QWebPage;

class PriceGrabber : public QObject
{
    Q_OBJECT
public:
    static PriceGrabber *queue(const QUrl &url);
    static void triggerQueue();

    virtual ~PriceGrabber();

signals:
    void grabSucceeded(int price);
    void grabFailed(const QString &error);

protected slots:
    void me_loadFinished(bool ok);

protected:
    PriceGrabber(const QUrl &url);

    void start();
    void stop();

    const bool grab(int &price);

    void retrieveGrab(
        const QString &host
    ,   QString &grabSelector
    ,   QString &grabPriceRE);

    const bool retrievePrice(
        const QString &grabSelector
    ,   const QString &grabPriceRE
    ,   int &price);

    static void unbatch(
        PriceGrabber *priceGrabber
    ,   const bool retriggerQueue = true);
    static void dequeue(
        PriceGrabber *priceGrabber
    ,   const bool retriggerQueue = true);

    static void cache(
        PriceGrabber *priceGrabber
    ,   const int price);

protected:
    static QQueue<PriceGrabber*> m_queue;

    static QSet<PriceGrabber*> m_batch;
    static QSet<QUrl> m_batchUrls;

    static int m_maxBatchSize;

    static QMap<QString, int> m_cache;
    static QMap<QString, QTime> m_times;

    static int m_maxCacheTime; // in secs


    QWebPage *m_page;
    QWebFrame *m_frame;

    const QUrl m_url;
};

#endif // PRICEGRABBER_H
